package com.thingcom.delinrobot.main.device;

import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.android.tu.loadingdialog.LoadingDailog;
import com.bigkoo.pickerview.adapter.ArrayWheelAdapter;
import com.contrarywind.view.WheelView;
import com.gizwits.gizwifisdk.api.GizWifiDevice;
import com.gizwits.gizwifisdk.enumration.GizWifiDeviceNetStatus;
import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode;
import com.thingcom.delinrobot.Common.Constant;
import com.thingcom.delinrobot.Common.Frame.FrameUtils;
import com.thingcom.delinrobot.Common.Frame.GetWorkingArea;
import com.thingcom.delinrobot.Common.Frame.SetWorkingArea;
import com.thingcom.delinrobot.Common.pjo.FrameType;
import com.thingcom.delinrobot.Data.GizManger;
import com.thingcom.delinrobot.R;
import com.thingcom.delinrobot.base.BaseBackFragment;
import com.thingcom.delinrobot.utils.HexStrUtils;
import com.thingcom.delinrobot.utils.HexUtil;
import com.thingcom.delinrobot.utils.MyLog;
import com.thingcom.delinrobot.utils.PreferencesUtil;
import com.thingcom.delinrobot.view.SimpleToolbar;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.thingcom.delinrobot.Common.Constant.ROBOT_VERSION;
import static com.thingcom.delinrobot.utils.AppUtils.hideSoftKeyboard;

/**
 * author : YuFeng
 * e-mail : 923462992@qq.com
 * date   : 2019/11/14
 */
public class MowingAreaBackFragment extends BaseBackFragment implements GizManger.myGizWifiDeviceListener{

    @BindView(R.id.toolbar_working_area)
    SimpleToolbar toolbarWorkingArea;
    @BindView(R.id.btn_set_data)
    Button btnSetData;
    @BindView(R.id.wheel_working_area)
    WheelView wheelWorkingArea;
    private int version;
    private LoadingDailog dialog;

    public static MowingAreaBackFragment newInstance(int a) {
        Bundle bundle = new Bundle();
        bundle.putInt(ROBOT_VERSION,a);
        MowingAreaBackFragment fragment = new MowingAreaBackFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_back_working_area, container, false);
        unbinder = ButterKnife.bind(this, view);
        toolbarWorkingArea.setMyLeftIcon(R.drawable.toolbar_back_two_selector);
        toolbarWorkingArea.setMinimumHeight(42);
        toolbarWorkingArea.setBackgroundColor(getResources().getColor(R.color.black_main));
        toolbarWorkingArea.setTitleStyle(getResources().getColor(R.color.white_main),13);
        toolbarWorkingArea.setLeftIconClickListener(view1 -> {
            hideSoftKeyboard(_mActivity);
            start(DeviceMainFragment.newInstance(),3);
    });
        GizManger.getInstance().setmCallback(this);
        GetWorkingArea getWorkingTime = new GetWorkingArea("00000000");
        GizManger.getInstance().GizWrite(getWorkingTime.parse());
        initView();
        return view;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle!=null){
            version =bundle.getInt(ROBOT_VERSION);
            MyLog.i("面积", "onCreate: "+version);
        }
    }
    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    public boolean onBackPressedSupport() {
        start(DeviceMainFragment.newInstance(),3);
        return true;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timer!=null){
            timer.cancel();
        }
    }

    private void initView() {
       wheelWorkingArea.setCyclic(true);
        int area;
        switch (version){
           case 18:
           default:
               area =600;
               break;
           case 19:
               area =1000;
               break;
           case 20:
               area =1500;
               break;
       }

        final List<String> mAreaItems = new ArrayList<>();
       for(int i = 0; i<= area; i+=50){
           mAreaItems.add(i+"m²/"+0.000247*i+"acre");
       }
        wheelWorkingArea.setTextSize(30);
        wheelWorkingArea.setItemsVisibleCount(5);
        wheelWorkingArea.setAdapter(new ArrayWheelAdapter(mAreaItems));
        wheelWorkingArea.setTextColorCenter(Color.WHITE);
        wheelWorkingArea.setOnItemSelectedListener(index -> {
//                ToastUtil.showToast(getContext(), "" + mAreaItems.get(index));
        });
    }


    @OnClick(R.id.btn_set_data)
    public void onViewClicked() {
        int area = wheelWorkingArea.getCurrentItem()*50;
        PreferencesUtil.getInstance(getContext()).putInt(Constant.GRASS_AREA,area);
        MyLog.i("12345", "onViewClicked: "+area);
        byte[] dataArea = HexUtil.intToBytes(area,2);
        SetWorkingArea setWorkingArea = new SetWorkingArea("00000000",dataArea);
        GizManger.getInstance().GizWrite(setWorkingArea.parse());
        LoadingDailog.Builder loadBuilder=new LoadingDailog.Builder(getContext())
                .setCancelable(false)
                .setCancelOutside(false);
        dialog=loadBuilder.create();
        dialog.show();
        timer.start();

    }

    @Override
    public void didSetSubscribe(GizWifiErrorCode result, GizWifiDevice device, boolean isSubscribed) {

    }

    @Override
    public void didReceiveData(GizWifiErrorCode result, GizWifiDevice device, ConcurrentHashMap<String, Object> dataMap, int sn) {
        if (dataMap.get("binary") != null) {
//            ConcurrentHashMap<String, Object> map = (ConcurrentHashMap<String, Object>) dataMap.get("binary");
            // 扩展数据点，key为"kuozhan"
            byte[] bytes = (byte[]) dataMap.get("binary");
            String string = HexStrUtils.bytesToHexString(bytes);
            MyLog.i("收到数据", string);
            byte[] dataArea;
            FrameType identify = FrameUtils.getDataIdentifyEnum(bytes);
//            FrameUtils.sendEventByDataIdentify(identify,bytes);
            if (identify!=null){
                switch (identify) {
                    case TYPE_FRAME_ROBOT_WORK_AREA_READ:
                        dataArea = FrameUtils.getDataArea(bytes);
                        String mainInfo = HexStrUtils.bytesToHexString(dataArea);
                        int area = Integer.valueOf(mainInfo.substring(0, 4), 16);
                        MyLog.i("area", "didReceiveData: "+"area："+area);
                        switch (area){
                            case 0:
                                wheelWorkingArea.setCurrentItem(0);
                                break;
                            case 50:
                                wheelWorkingArea.setCurrentItem(1);
                                break;
                            case 100:
                                wheelWorkingArea.setCurrentItem(2);
                                break;
                            case 150:
                                wheelWorkingArea.setCurrentItem(3);
                                break;
                            case 200:
                                wheelWorkingArea.setCurrentItem(4);
                                break;
                            case 250:
                                wheelWorkingArea.setCurrentItem(5);
                                break;
                            case 300:
                                wheelWorkingArea.setCurrentItem(6);
                                break;
                            case 350:
                                wheelWorkingArea.setCurrentItem(7);
                                break;
                            case 400:
                                wheelWorkingArea.setCurrentItem(8);
                                break;
                            case 450:
                                wheelWorkingArea.setCurrentItem(9);
                                break;
                            case 500:
                                wheelWorkingArea.setCurrentItem(10);
                                break;
                            default:
                                break;
                        }
                        break;
                    case TYPE_FRAME_ROBOT_WORK_AREA_SET:
                        dataArea = FrameUtils.getDataArea(bytes);
                        String ok = HexStrUtils.bytesToHexString(dataArea);
                        MyLog.i("接受", "didReceiveData: "+"ok"+ok);
                        if (timer!=null){
                            timer.cancel();
                        }
                        if (dialog!=null){
                            dialog.dismiss();
                        }
                        if (ok.equals("01")){
                            Toast.makeText(getContext(),getString(R.string.success_toast), Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getContext(),getString(R.string.fail_toast), Toast.LENGTH_SHORT).show();
                        }
                        break;
                    default:
                        break;
                }
            }



        }
    }

    @Override
    public void didGetHardwareInfo(GizWifiErrorCode result, GizWifiDevice device, ConcurrentHashMap<String, String> hardwareInfo) {

    }

    @Override
    public void didSetCustomInfo(GizWifiErrorCode result, GizWifiDevice device) {

    }

    @Override
    public void didUpdateNetStatus(GizWifiDevice device, GizWifiDeviceNetStatus netStatus) {

    }

    /**
     * 开始进度
     */

    private CountDownTimer timer = new CountDownTimer(10000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
        }

        @Override
        public void onFinish() {
            Toast.makeText(getContext(),"time out ",Toast.LENGTH_SHORT).show();
            if (dialog!=null){
                dialog.dismiss();
            }
        }
    };
}
